let id=0;
class Actor{
    constructor(parallelSize=3){
        this._worker=new Worker(w.workerUrl);
        this.parallelSize=parallelSize;
        this.id=id++;
        this.name="Actor"+this.id;
        this._worker.addEventListener('message',this.recieve.bind(this),false);
        this._callbacks= new Map();
        this._mailbox=[];
        this._counter=0;
    }
    get mailbox(){
        return this._mailbox;
    }
    set name(value){
        this._name=value;
    }
    get name(){
        return this._name;
    }
    get worker(){
        return this._worker;
    }
    get busy(){
        return this._callbacks.size>0;
    }
    recieve(ev){
        const message = ev.data;
        const id=message.id;
        const callback = message.id?this._callbacks.get(id):null;
        if(callback){
            callback(message);
        }
        this._callbacks.delete(id);
        this.active();
    }
    send(message,callback){
        if(!message.id){
            message.id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10);
        }
        this._callbacks.set(message.id,callback);
        this.mailbox.push(message);
        this.active();
    }
    active(){
        let message=this._popMessage();
        if(message){
            this.worker.postMessage(message);
            if(this._callbacks.size-this.mailbox.length<this.parallelSize){
                this.active();
            }
        }   
    }
    _popMessage(){
        return this.mailbox.pop();
    }
    clear(){
        this._tasks=[];
        this._callbacks.clear();
    }
}
export default Actor;